import Vue from 'vue';
import VueRouter from 'vue-router';
import LoginView from '../views/LoginView.vue';
import HomeView from '../views/HomeView.vue';
import PublicActivitiesView from '../views/PublicActivitiesView.vue';
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue';
import ActivityManagementView from '../views/ActivityManagementView.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: PublicActivityDetailView
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: {
      requiresAuth: true,
      roles: ['admin']
    }
  }
];

const router = new VueRouter({
  // 移除对 import.meta.env.BASE_URL 的引用
  mode: 'history', 
  routes
});

router.beforeEach((to, from, next) => {
  const userRole = sessionStorage.getItem('userRole');
  const isAuthenticated = userRole!== null;
  const requiresAuth = ['public-activities', 'public-activity-detail', 'activity-management'].includes(to.name);

  if (requiresAuth &&!isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

export default router;